// pages/myOrder/myOrder.js
import api from '../../utils/request/api'
const util = require('../../utils/util.js');
import {
  courier
} from '../../utils/request/apiurl'

var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchGood: {
      page: 1,
      size: 10,
      pages: 0
    },
    orderList: [{
      id: 1,
      name: '全部',
      value: "",
      current: true
    },
    {
      id: 2,
      name: '配送中',
      value: 0,
      current: false
    },
    {
      id: 3,
      name: '已送达',
      value: 1,
      current: false
    }
    ],
    winHeight: "", //窗口高度
    currentTab: 0, //预设当前项的值
    scrollLeft: 0, //tab标题的滚动条位置
    goodList: [],
	isRequest:false,
	uid:'',
  urlImg:[],//分隔图片存地
  orderArray:[],//订单号数组
    tempArr:null,//临时订单号存放
    checkArr:[],//选中的订单号数据
    allCheckIs:false,//全选按钮默认false
    flag:false,
  },
  onLoad: function (options) {
	  var userInfo=wx.getStorageSync('userInfo')
	  this.setData({
		  uid:userInfo.uid
	  })
    var that = this;
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 180;
        // console.log(calc)
        that.setData({
          winHeight: calc
        });
      }
    });
    //判断当前tag
    this.setData({
      goodList: []
    })
    this.getList()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
  	wx.showNavigationBarLoading() //在标题栏中显示加载
  	this.setData({
  	  goodList: [],
	  searchGood: {
	    page: 1,
	    size: 10,
	    pages: 0
	  },
  	})
  	this.getList()
  	setTimeout(function() {
  		wx.hideNavigationBarLoading() //完成停止加载
  		wx.stopPullDownRefresh() //停止下拉刷新
  	}, 1500);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.isRequest && this.data.searchGood.page < this.data.searchGood.pages) {
    this.setData({
      searchGood: {
        page: this.data.searchGood.page + 1,
        size: 10,
        pages: this.data.searchGood.pages
      }
    })
    	this.getList()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //选中全选按钮
  checkboxChangeAll(e) {
    //初始化数据
    this.setData({
      checkArr: [],
    })
    if (this.data.allCheckIs){
      this.data.goodList.map((item, index) => {
        console.log("goodListitem全选哦", item, index)
          var itemType = "goodList["+ index + "].type"
          this.setData({
            [itemType]:null
          })
      })
      this.setData({
        allCheckIs:false,
      })
    }else{
      this.data.goodList.map((item, index) => {
        console.log("goodListitem全选哦", item, index)
        var itemType = "goodList[" + index + "].type"
        this.setData({
          [itemType]: 1
        })
      })
      this.setData({
        allCheckIs: true
      })
    }
    //把选中的订单号存起来
    this.data.goodList.map((item, index) => {
      if (item.type == 1) {//选中
        this.data.checkArr.push(item.orderNumAll);
      }
    })
    console.log("adsadadsadad", this.data.allCheckIs, this.data.goodList)
    console.log("数据+++++++++", this.data.checkArr.join(","), this.data.checkArr)
    // this.data.goodList.map((item, index) => {
    //   console.log("goodListitem全选哦", item, index)
    //   //反选
    //   // if (item.type === null) {
    //   //   var itemType = "goodList["+ index + "].type"
    //   //   this.setData({
    //   //     [itemType]:1
    //   //   })
    //   // }else{
    //   //   var itemType = "goodList[" + index + "].type"
    //   //   this.setData({
    //   //     [itemType]: null
    //   //   })
    //   // }
    // })
  },
  //选中checkBox事件
  checkboxChange: function (e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value,e);
    var obj = e.detail.value.join(",");
    this.setData({
      tempArr: obj,
    })
  },
  checkTab(e){
    //初始化数据
    this.setData({
      checkArr:[],
    })
    let idx 
    if (e.currentTarget){
      idx = e.currentTarget.dataset.id;//商品索引值
    }else{
      idx = e;
    }
    if(this.data.goodList[idx].type === null){//未选中
      var itemType = "goodList[" + idx + "].type"
      this.setData({
        [itemType]: 1
      })
    }else{
      var itemType = "goodList[" + idx + "].type"
      this.setData({
        [itemType]: null
      })
    }
    //把选中的订单号存起来
    this.data.goodList.map((item, index) => {
      if (item.type == 1) {//选中
        this.data.checkArr.push(item.orderNumAll);
      }
    })
    console.log("adsadadsadad", this.data.allCheckIs, this.data.goodList)
    console.log("数据+++++++++", this.data.checkArr.join(","), this.data.checkArr)
    //循环判断是否全部选中
    for (let i in this.data.goodList) {
      if (this.data.goodList[i].type === null) {
       return this.setData({
         flag: false,
          allCheckIs: false
        })
      }else {
        this.setData({
          flag : true
        })
      }
    }
    this.setData({
      allCheckIs: this.data.flag,
    })
    // if (this.data.tempArr == "" || this.data.tempArr == null){
    //   // this.data.orderArray.splice(idx, 1);//删除数组
    //   // for (let i in this.data.orderArray) {
    //   // }
    //     var item = "orderArray[" + idx + "]"
    //     this.setData({
    //       [item]:null,
    //     })
    //   //循环是否全部选中
    //   this.data.goodList.map((item, index) => {
    //     console.log("goodListitem全选哦", item, index)
    //     if (item.type === null) {
    //       var itemType = "goodList[" + index + "].type"
    //       this.setData({
    //         [itemType]: 1
    //       })
    //     } else {
    //       var itemType = "goodList[" + index + "].type"
    //       this.setData({
    //         [itemType]: null
    //       })
    //     }
    //   })
    // } else {//选中
    //   var item = "orderArray[" + idx + "]"
    //   this.setData({
    //     [item]: this.data.tempArr
    //   })
    // }
    // //forEach循环把null清除掉返回新数组
    // var objOrderObj = [];
    // this.data.orderArray.map((item,index)=>{
    //     console.log("item",item,index)
    //     if(item !== null){
    //       objOrderObj.push(item);
    //     }
    // })
    // this.setData({
    //   checkArr: objOrderObj,
    // })
    // console.log("数据+++++++++", this.data.checkArr.join(","), objOrderObj)
  },
  // 滚动切换标签样式
  switchTab: function (e) {
    console.log("标签页",e)
    this.setData({
      currentTab: e.detail.current,
      allCheckIs:false,
    });
    this.checkCor();
    // console.log(2)
    this.getList(1)
  },
  // 点击标题切换当前页时改变样式allCheckIs
  swichNav: function (e) {
    console.log(e,"=====>")
    var cur = e.target.dataset.current;
    if (this.data.currentTaB == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur
      })
    }
    this.setData({
      searchGood: {
       page:  this.data.searchGood.page,
       size: this.data.searchGood.size,
       pages:  this.data.searchGood.pages,
      },
      goodList: []
    })
    // console.log(1)
    this.getList(1)
  },
  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function () {
    if (this.data.currentTab > 2) {
      this.setData({
        scrollLeft: 56 * this.data.currentTab
      })
      // console.log(this.data.scrollLeft)
    } else {
      this.setData({
        scrollLeft: 0
      })
    }
  },
  //获取订单列表
  getList(changeType) {
	  // console.log(changeType,'changeTypechangeType')
    let type = this.data.orderList[this.data.currentTab].value
    api.post(courier.list, {
      page: this.data.searchGood.page,
      size: this.data.searchGood.size,
      uid: this.data.uid,
      type: type
    }).then(res => {
      // console.log(res)
      let list = res.rows
      if (changeType === 1) {
        this.setData({
          goodList: list
        })
        // 初始化数据
        this.setData({
          orderArray:[],
        })
        //checkbox定义空数组
        for (let i in this.data.goodList) {
          this.data.orderArray.push(null)
        }
      } else {
        this.setData({
          goodList: [...this.data.goodList, ...list]
        })
      }
      let pages = res.total / this.data.searchGood.size
      this.setData({
        searchGood: {
          page: this.data.searchGood.page,
          size: this.data.searchGood.size,
          pages: pages
        }
      })
      // console.log(this.data.goodList)
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none'
      })
    })
  },
  //删除订单
  deleteOrder(e) {
    let id = e.target.dataset['id']
    let that = this
    wx.showModal({
      title: '删除订单',
      content: '是否确认删除这个订单？',
      success: function (res) {
        if (res.confirm) {
          api.post(courier.deleteOrder, {
            OrderNoAll: id
          }).then(res => {
            that.setData({
              goodList: []
            })
			
            that.getList(1)
          }).catch(err => {
            wx.showToast({
              title: err.message,
              icon: 'none'
            })
          })
        }
      }
    })
  },
  //联系电话
  callPhone(e) {
    let phone = e.target.dataset['phone']
    // console.log(phone)
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  //确认送达
  sureOrder(e) {
	  // console.log(e)
    // let id = e.target.dataset['id']
    // if (this.data.checkArr.length == 0 || this.data.sureOrder == null){
    //   return wx.showToast({
    //     title: '未选择商品',
    //     icon:'none'
    //   })
    // }
    var orderId;
    //判断是否有选中的有 id
    if (this.data.checkArr.length == 0 || this.data.checkArr == null){//没有选中
      orderId = e.target.dataset['id']
    }else{
      orderId = this.data.checkArr.join(",")
    }
    let that = this
    wx.showModal({
      title: '确认送达',
      content: '是否确认订单已经送达？',
      success: function (res) {
        if (res.confirm) {
          api.post(courier.success, {
            OrderNoAll: orderId
          }).then(res => {
            that.setData({
              goodList: [],
            })
			// wx.navigateTo({
			// 	url: '../myOrder-courier/myOrder-courier'
			// })
            that.getList(2)
          }).catch(err => {
            wx.showToast({
              title: err.message,
              icon: 'none'
            })
          })
        }
      }
    })
  },
  footerTap: app.footerTap
})